package com.atguigu.day08;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public class Flink15_SQL_OverWindow {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        // 2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //设置本地时区
        Configuration configuration = tableEnv.getConfig().getConfiguration();
        configuration.setString("table.local-time-zone", "GMT");


        //TODO 3.在建表语句中指定事件时间字段
        tableEnv.executeSql("create table sensor(" +
                "id string," +
                "ts bigint," +
                "vc int," +
//                "et as to_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'))," +
                //TODO 在Flink1.13.0版本中Over开窗中无法使用 1.13.6已修复
                "et as to_timestamp_ltz(ts,3)," +
                "watermark for et as et - interval '3' second" +
                ") with("
                + "'connector' = 'filesystem',"
                + "'path' = 'input/sensor-sql.txt',"
                + "'format' = 'csv'"
                + ")"
        );

        //OverWindow
      /*  tableEnv.executeSql("select " +
                " id," +
                " ts," +
                " vc," +
                " sum(vc) over(partition by id order by et)" +
                " from sensor" +
                "").print();*/

      //OverWindow另一种写法，这样写的好处是，一次定义多次使用，不需要重复再去定义窗口
      tableEnv.executeSql("select " +
              " id," +
              " ts," +
              " vc," +
              " sum(vc) over w as vcSum," +
              " count(vc) over w as vcCount" +
              " from sensor " +
              " window w as (partition by id order by et)").print();


    }
}
